package com.xuzhijie.pms.controller;

import com.xuzhijie.pms.common.Result;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@RestController
public class ImageController {

    @Value("${file.upload-dir}")
    private String uploadDir;

    @Value("${file.req-dir}")
    private String reqDir;

    @Value("${server.port}")
    private String port;

    @Value("${file.ip}")
    private String ip;

    @PostMapping("/upload")
    public String uploadFile(@RequestParam("file") MultipartFile file) {
        try {
            // 获取文件名
            String newFileName = UUID.randomUUID().toString() + "_" + file.getOriginalFilename();
            // 文件保存路径，这里假设保存在当前项目的upload文件夹下
            String filePath = uploadDir;
            // 如果目录不存在，则创建目录
            File dest = new File(filePath +"\\"+ newFileName);
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }
            // 保存文件
            file.transferTo(dest);
            // 返回图片路径
            String fileUrl = ip + port + "/"+ reqDir +"/" + newFileName;
            System.out.println(fileUrl);
            return fileUrl;
        } catch (IOException e) {
            e.printStackTrace();
            return "上传失败";
        }
    }

    @PostMapping("/upload-images")
    public Result handleImageUpload(@RequestParam("images") MultipartFile[] images) {
        // 指定保存文件的目录
        System.out.println(images);
        // 创建保存文件的目录
        Path directory = Paths.get(uploadDir);
        if (!Files.exists(directory)) {
            try {
                Files.createDirectories(directory);
            } catch (IOException e) {
                e.printStackTrace();
                // 返回空列表表示上传失败
                return Result.error();
            }
        }

        List<String> uploadedPaths = new ArrayList<>();
        // 处理上传的照片数组
        for (MultipartFile image : images) {
            // 构造文件路径
            String newFileName = UUID.randomUUID().toString() + "_" + image.getOriginalFilename();
            Path filePath = Paths.get(uploadDir, newFileName);
            try {
                // 将文件保存到指定目录
                Files.copy(image.getInputStream(), filePath);
                // 将新路径添加到列表中
                String fileUrl = ip + port + "/"+ reqDir +"/" + newFileName;
                uploadedPaths.add(fileUrl);
            } catch (IOException e) {
                e.printStackTrace();
                // 返回空列表表示上传失败
                return Result.error();
            }
        }
        System.out.println(uploadedPaths);
        return Result.success(uploadedPaths);
    }


    // 文件存储路径，这里假设图片存储在F:/pmsimage/下
    private static final String FILE_DIRECTORY = "F:/pmsimage/";

    // 图片访问接口，通过图片名称获取图片
    @GetMapping("/image/{imageName}")
    public Resource getImage(@PathVariable String imageName) {
        try {
            // 构造文件路径
            Path filePath = Paths.get(FILE_DIRECTORY).resolve(imageName);
            // 加载文件资源
            Resource resource = new UrlResource(filePath.toUri());

            // 检查文件是否存在并且可读
            if (resource.exists() && resource.isReadable()) {
                // 设置响应头
                HttpHeaders headers = new HttpHeaders();
                headers.add(HttpHeaders.CONTENT_TYPE, "image/jpeg");
                return resource;
            } else {
                // 文件不存在或者不可读
//                return new ResponseEntity<>(HttpStatus.NOT_FOUND);
                return null;
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
//            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
            return null;
        }

    }

}
